<template>
  <div class="common-page page-policy-article" v-loading.fullscreen="loading">
    <div class="common-page__head">
      <comp-paths class="route" :paths="['/policyUp', $route.fullPath]"></comp-paths>
      <div class="title" v-if="article">
        <span class="text">{{ article.title }}</span>
        <span class="flag" v-for="tag in article.tags" :key="tag.id">{{ tag.name }}</span>
      </div>
      <div class="title" v-else></div>
    </div>
    <div class="common-page__body common-form" v-if="article">
      <div class="rows">
        <div class="row row--head">
          <div class="name">基本信息</div>
          <div class="value">
            <span class="button button--edit" @click="setPolicy()">编辑</span>
          </div>
        </div>
        <div class="row row--2x">
          <div class="name">政策标题</div>
          <div class="value">{{ article.policyTitle }}</div>
        </div>
        <div class="row">
          <div class="name"></div>
          <div class="value"></div>
        </div>
<!--        <div class="row">-->
<!--          <div class="name">信息编号</div>-->
<!--          <div class="value">{{ article.policyNo }}</div>-->
<!--        </div>-->
        <div class="row">
          <div class="name">政策来源</div>
          <div class="value">{{ article.policySource }}</div>
        </div>
        <div class="row">
          <div class="name">政策要点</div>
          <div class="value">{{ article.policyPoints }}</div>
        </div>
        <div class="row">
          <div class="name">发文时间</div>
          <div class="value">{{ article.publishTimeStr }}</div>
        </div>
<!--        <div class="row row&#45;&#45;2x">-->
<!--          <div class="name">信息摘要</div>-->
<!--          <div class="value">{{ article.summary }}</div>-->
<!--        </div>-->
        <div class="row">
          <div class="name">政策正文</div>
          <div class="value">
            <span class="button" @click="action('article-content', true)">查看</span>
          </div>
        </div>
<!--        <div class="row">-->
<!--          <div class="name">信息来源</div>-->
<!--          <div class="value">{{ article.referer }}</div>-->
<!--        </div>-->
<!--        <div class="row">-->
<!--          <div class="name">信息原文</div>-->
<!--          <div class="value">{{ article.source }}</div>-->
<!--        </div>-->
<!--        <div class="row">-->
<!--          <div class="name">信息作者</div>-->
<!--          <div class="value">{{ article.author }}</div>-->
<!--        </div>-->
<!--        <div class="row">-->
<!--          <div class="name">信息分类</div>-->
<!--          <div class="value">-->
<!--            <span class="text" v-for="tag in article.tags" :key="tag.id">{{ tag.name }}</span>-->
<!--          </div>-->
<!--        </div>-->
<!--        <div class="row">-->
<!--          <div class="name">申报起止日期</div>-->
<!--          <div class="value">{{ article.startAt + " ~ " + article.endAt }}</div>-->
<!--        </div>-->
<!--        <div class="row">-->
<!--          <div class="name">信息权重</div>-->
<!--          <div class="value">{{ article.weight }}</div>-->
<!--        </div>-->
<!--        <div class="row">-->
<!--          <div class="name">发布时间</div>-->
<!--          <div class="value">{{ article.publishTimeStr }}</div>-->
<!--        </div>-->
<!--        <div class="row">-->
<!--          <div class="name">信息浏览量</div>-->
<!--          <div class="value">{{ article.views }}</div>-->
<!--        </div>-->
      </div>
    </div>
<!--    <div class="common-page__foot" v-if="article">-->
<!--      <el-button type="warning" size="small" icon="el-icon-s-promotion" @click="pushArticle()">信息推送</el-button>-->
<!--    </div>-->
    <comp-dialog title="编辑基本信息" ref="articleSetForm">
      <el-form size="small" label-width="98px" style="margin-right: 20px" @submit.native.prevent v-if="articleSetForm">
        <!--                <el-form-item label="信息封面：">-->
        <!--                    <img style="display: block; margin: 0 10px 10px 0; max-width: 120px; height: 60px" :src="articleSetForm.banner" v-if="articleSetForm.banner" />-->
        <!--                    <el-button type="plain" icon="el-icon-plus" @click="setPolicy('upload-banner')">{{ articleSetForm.banner ? "更换图片" : "选择图片" }}</el-button>-->
        <!--                </el-form-item>-->
        <el-form-item label="政策标题：" required>
          <el-input ref="articleSetFormTitle" type="textarea" v-model="articleSetForm.policyTitle" style="width: 640px"
                    placeholder="请输入" :maxlength="100" :rows="2" resize="none" :readonly="loading"
                    @change="setPolicy('validate')"></el-input>
        </el-form-item>

        <el-form-item label="政策来源：" required>
          <el-input  v-model="articleSetForm.policySource" style="width: 640px" placeholder="请输入政策单位" :maxlength="100" :readonly="loading" @change="addPolicy('validate')"></el-input>
        </el-form-item>
        <el-form-item label="政策要点：" >
          <el-input  v-model="articleSetForm.policyPoints" style="width: 640px" placeholder="请输入政策要点" :maxlength="100" :readonly="loading" @change="addPolicy('validate')"></el-input>
        </el-form-item>
        <el-form-item label="发文时间：" required>
          <el-date-picker  v-model="articleSetForm.publishTime"
                           type="datetime"
                           style="width: 640px"
                           placeholder="请输入发文时间"
                           :value-format="'timestamp'"
                           :readonly="loading" @change="addPolicy('validate')"></el-date-picker>
        </el-form-item>
        <!--                <el-form-item label="信息摘要：">-->
        <!--                    <el-input type="textarea" v-model="articleSetForm.summary" style="width: 640px" placeholder="请输入" :maxlength="200" :rows="5" resize="none" :readonly="loading" @change="setPolicy('validate')"></el-input>-->
        <!--                </el-form-item>-->
        <el-form-item label="政策正文：">
          <comp-html-editor ref="articleSetFormContentEditor" style="width: 640px; height: 300px" editing
                            :content="articleSetForm.policyContent"></comp-html-editor>
        </el-form-item>
        <!--                <el-form-item label="信息来源：">-->
        <!--                    <el-input v-model="articleSetForm.referer" style="width: 640px" placeholder="请输入" :maxlength="100" :readonly="loading" @change="setPolicy('validate')"></el-input>-->
        <!--                </el-form-item>-->
        <!--                <el-form-item label="信息原文：">-->
        <!--                    <el-input v-model="articleSetForm.source" style="width: 640px" placeholder="请输入" :maxlength="100" :readonly="loading" @change="setPolicy('validate')"></el-input>-->
        <!--                </el-form-item>-->
        <!--                <el-form-item label="信息作者：">-->
        <!--                    <el-input v-model="articleSetForm.author" style="width: 640px" placeholder="请输入" :maxlength="100" :readonly="loading" @change="setPolicy('validate')"></el-input>-->
        <!--                </el-form-item>-->
        <!--                <el-form-item label="信息分类：">-->
        <!--                    <el-select v-model="articleSetForm.tag.id" style="width: 640px" placeholder="请选择" @change="setPolicy('validate')">-->
        <!--                        <el-option v-for="data in tags" :key="data.id" :label="data.name" :value="data.id"></el-option>-->
        <!--                    </el-select>-->
        <!--                </el-form-item>-->
        <!--                <el-form-item label="申报日期：">-->
        <!--                    <el-date-picker type="date" v-model="articleSetForm.startTime" style="width: 306px" format="yyyy年M月d日" value-format="timestamp" placeholder="起始日期" :clearable="false" :readonly="loading" @change="addArticle('validate')"></el-date-picker>-->
        <!--                    <span style="margin: 0 0.5em">至</span>-->
        <!--                    <el-date-picker type="date" v-model="articleSetForm.endTime" style="width: 306px" format="yyyy年M月d日" value-format="timestamp" placeholder="截止日期" :clearable="false" :readonly="loading" @change="addArticle('validate')"></el-date-picker>-->
        <!--                </el-form-item>-->
        <!--                <el-form-item label="信息权重：">-->
        <!--                    <el-input v-model="articleSetForm.weight" style="width: 640px" placeholder="请输入" :readonly="loading" @change="setPolicy('validate')"></el-input>-->
        <!--                </el-form-item>-->
        <!--                <el-form-item label="发布时间：" required>-->
        <!--                    <el-date-picker-->
        <!--                        v-model="articleSetForm.publishTime"-->
        <!--                        type="datetime"-->
        <!--                        value-format="timestamp"-->
        <!--                        :readonly="loading"-->
        <!--                    ></el-date-picker>-->
        <!--                </el-form-item>-->
        <!--                <el-form-item label="信息状态：">-->
        <!--                    <el-select v-model="articleSetForm.published" style="width: 640px" placeholder="请选择" @change="setPolicy('validate')">-->
        <!--                        <el-option v-for="data in env.articlePublisheds" :key="data.id" :label="data.name" :value="data.value"></el-option>-->
        <!--                    </el-select>-->
        <!--                </el-form-item>-->
        <el-form-item>
          <el-button type="primary" icon="el-icon-check" @click="setPolicy('submit')">保存</el-button>
          <el-button type="plain" icon="el-icon-close" @click="setPolicy('end')">放弃</el-button>
        </el-form-item>
      </el-form>
    </comp-dialog>
    <comp-dialog title="政策正文" width="600px" height="80vh" ref="articleContent">
      <comp-html-editor style="height: 100%" ref="articleContentEditor" :content="article.policyContent" v-if="article">
        <template #foot="scope">
          <el-button type="plain" size="small" icon="el-icon-close" @click="action('article-content', false)">关闭
          </el-button>
        </template>
      </comp-html-editor>
    </comp-dialog>
<!--    <comp-dialog title="信息推送" width="380px" ref="articlePushForm">-->
<!--      <el-form size="small" label-width="98px" @submit.native.prevent v-if="articlePushForm">-->
<!--        <el-form-item label="推送标题：" required>-->
<!--          <div style="margin-right: 20px; padding: 5px 0; line-height: 1.5">{{ articlePushForm.title }}</div>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="推送用户：">-->
<!--          <el-select v-model="articlePushForm.clientRoleToPush" style="width: 160px" placeholder="请选择">-->
<!--            <el-option v-for="data in env.userRoles" :key="data.id" :label="data.name" :value="data.value"></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item>-->
<!--          <el-button type="primary" icon="el-icon-check" @click="pushArticle('submit')">推送</el-button>-->
<!--          <el-button type="plain" icon="el-icon-close" @click="pushArticle('end')">放弃</el-button>-->
<!--        </el-form-item>-->
<!--      </el-form>-->
<!--    </comp-dialog>-->
  </div>
</template>

<script>
import mixin from "../mixin";
import {string, int, deepCopy, toMagicImgURL, selectFile, cache} from "../util";
import env from "@/env";

export default {
  name: "page-up-policy",
  title: "信息详情",
  nodes: ["/menu/policyUp"],
  childs: [],
  mixins: [mixin],
  data: () => ({
    loading: false,
    articleId: "",
    article: null,
    articleSetForm: null,
    articleContentSetForm: null,
    articlePushForm: null,
    tags: [],
    baseApiUrl: env.xhrPrefix,
  }),
  methods: {
    action(name, data) {
      if (this.loading) return;
      if (name === "article-content") {
        if (data) {
          this.$refs.articleContent.init();
          this.$nextTick(() => this.$refs.articleContentEditor.init());
        } else {
          this.$refs.articleContentEditor.destroy();
          this.$refs.articleContent.close();
        }
      }
    },
    setPolicy(action, data) {
      if (this.loading) return;
      let form = this.articleSetForm;
      console.log("setPolicy", form)
      if (!action || action === "start") {
        this.loading = true;
        this.plugins.user.getArticleOfTags({linage: 100, page: 1}).then((res) => {
          this.loading = false;
          if (res.code === 0) {
            this.tags = res.data.list.reduce((tags, tag) => {
              let type = this.env.articleTypes.find((type) => type.value === "policy");
              if (tag.tag.id === type.id) tags.push(tag);
              return tags;
            }, []);
            this.articleSetForm = deepCopy(this.article);
            this.setPolicy("validate");
            this.$refs.articleSetForm.init();
            this.$nextTick(() => this.$refs.articleSetFormTitle.focus());
            this.$nextTick(() => this.$refs.articleSetFormContentEditor.init());
          } else {
            this.plugins.modal.toast("加载失败<br>" + res.code + "：" + res.msg, "error");
          }
        });
      } else if (action === "validate") {
        let error = "";
        form.policyTitle = string(form.policyTitle).trim();
        error = error || (form.policyTitle ? "" : "请输入信息标题！");
        error = error || (form.policySource ? "" : "请输入信息来源！");
        error = error || (form.publishTime ? "" : "请选择发文时间！");
        form.policyContent = string(() => this.$refs.articleSetFormContentEditor.getContent()) || string(form.policyContent);
        if (data) this.plugins.modal.toast(error, "error");
        return !error;
      } else if (action === "upload-banner") {
        if (!data) return selectFile("image/*").then((file) => {
          if (file.size > 5 * 1048576) this.plugins.modal.toast("图片过大，不能大于5MB哦！请重新选择。", "error");
          else this.setPolicy(action, file);
        });
        let timer = null;
        let progress = (event) => timer = clearTimeout(timer) || setTimeout(() => this.plugins.modal.toast("上传进度：" + event.percent + "%", "info"), 200);
        this.loading = true;
        this.plugins.user.uploadFile(data, "image", progress).then((res) => {
          this.loading = false;
          if (res.code === 0) {
            form.banner = this.baseApiUrl + "/user/sysStorage/getFile/" + res.data.id + "?id=" + res.data.id //toMagicImgURL(res.data.value, 120, 120);
            this.setPolicy("validate");
          } else {
            this.plugins.modal.alert("图片上传失败", res.code + "：" + res.msg, "error");
          }
        });
      } else if (action === "submit") {
        if (!this.setPolicy("validate", true)) return;
        this.loading = true;
        this.plugins.user.policySet(form).then((res) => {
          this.loading = false;
          if (res.code === 0) {
            this.plugins.modal.toast("添加成功！", "success");
            this.setPolicy("end");
            this.init();
          } else {
            this.plugins.modal.alert("添加失败", res.code + "：" + res.msg, "error");
          }
        });
      } else if (action === "end") {
        this.$refs.articleSetForm.close();
      }
    },
    pushArticle(action, data) {
      if (this.loading) return;
      let form = this.articlePushForm;
      if (!action || action === "start") {
        this.articlePushForm = deepCopy(this.article);
        this.articlePushForm.clientRoleToPush = this.env.userRoles[0].value;
        this.$refs.articlePushForm.init();
      } else if (action === "submit") {
        this.loading = true;
        this.plugins.user.pushArticle(form.id, form.clientRoleToPush).then((res) => {
          this.loading = false;
          if (res.code === 0) {
            this.plugins.modal.toast("推送成功！", "success");
            this.pushArticle("end");
            this.init();
          } else {
            this.plugins.modal.alert("推送失败", res.code + "：" + res.msg, "error");
          }
        });
      } else if (action === "end") {
        this.$refs.articlePushForm.close();
      }
    },
    destroy() {
      if (this.loading) return;
      return true;
    },
    init() {
      if (this.loading) return;
      let query = this.$route.query;
      let article = null;
      this.loading = true;
      this.articleId = query.policyId;
      this.article = cache(query.policyId);
      this.$root.$refs.navbar.init();
      this.plugins.user.call(async () => {
        let res = await this.plugins.user.init();
        if (res.code === 0) {
        }
        return res;
      }, async () => {
        if (this.access(this.$route.name)) return {code: 0};
        return this.env.xhrErrors.find((error) => error.code === 4);
      }, async () => {
        let res = await this.plugins.user.policyGet(query.policyId);
        if (res.code === 0) article = res.data;
        return res;
      }).then((res) => {
        this.loading = false;
        this.$root.$refs.navbar.init();
        if (res.code === 0) {
          this.article = cache(query.policyId, article);
        } else if (res.code === 2) {
          this.$root.$refs.navbar.login();
        } else {
          this.plugins.modal.alert("页面加载失败", res.code + "：" + res.msg, "error").then(() => this.$router.replace("/policy/articles"));
        }
      });
    },
  },
};
</script>

<style lang="scss">
.page-policy-article {
  overflow: hidden;
}
</style>
